<?php

/**
 * Controlleur Avance pour la gestion de l'authentification
 *
 * @category   McCube
 * @package    Controller
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 */
class McCube_Controller_Auth extends McCube_Controller{

    public function logout(){
        $this->session->destroy();
        header('Location:/');
    }

    public function login(){
        /* Check if session already exist and if she's not expired
         * -> If ok we get the user settings and return the authenticated view */
        if($user = $this->_getSession())
            return $this->render('authenticated');

        /* Get the form and proceed at the authentification
         * -> If something is wrong : return the form view */
        if($form = $this->_getForm())
            return $form->render();

        /* Authentification is ok we set the user in the session */
        $this->session->set('user', $this->user);
        $this->session->save();

        /* Return the authenticated view */
        if(!McCube_Router::getInstanceOf()->isAjaxRequest())
            return $this->render('authenticated');

        header('RELOADPAGE:1');
        exit;
    }

    protected function _getSession(){
        if($this->session->restore()){
            return $this->session->get('user');
        }
    }

    protected function _getUserQuery($form){
         return $this->database->select()
            ->table   ('users')
            ->fields  ('*')
            ->where   ('username =', $form->getValue('username'))
            ->andWhere('password =', $form->getValue('password'))
            ->limit   (1)
            ->exec()
        ;
    }

    protected function _getUser($form){
        $user = $this->_getUserQuery($form);
        if($user = $user->fetch())
            return $user;

        $this->session->addNotice('error','UserNotFound');
    }

    protected function _getForm(){
        $form = $this->getForm('login');
        if(!$form->isSent() || !$form->isValid()
            || !($this->user = $this->_getUser($form))
        ){
            return $form;
        }
    }

}